﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DO.Workflows
{
    public class ManualStart:WorkflowTrigger
    {
        #region Overrides of WorkflowComponentBase

        private ManualStartInstruction _Instruction;
        public override InstructionBase Instruction
        {
            get { return _Instruction; }
            set { _Instruction =(ManualStartInstruction)value; }
        }

        private ManualStartOutput _Output;
        public override ResultBase Output
        {
            get { return _Output; }
            set { _Output=(ManualStartOutput)value; }
        }

        #endregion

        public ManualStart():base()
        {
            this.ComponentName = "Manual start";
            this.Description = "Start workflow manually for test";

            this._Instruction=new ManualStartInstruction();
            this._Output=new ManualStartOutput();
        }

        #region Overrides of WorkflowTrigger

        public override TriggerType TriggerType
        {
            get { return TriggerType.ManualStart; }
        }

        public override bool CanRun()
        {
            if(this._Instruction.IsActive)
                return true;
            else
                return false;
        }

        public override void UpdateNextRun()
        {
            this._Instruction.IsActive = false;
        }

        public override ResultBase[] ProcessTrigger(ref WorkflowTriggerInstructionBase instruction)
        {
            if (instruction == null || instruction.GetType() != typeof(ManualStartInstruction))
                throw new Exception("Invalid instruction for timer");
            instruction.IsActive = false;
            DateTime now = DateTime.Now;
            ManualStartInstruction manualStartInstruction = (ManualStartInstruction)instruction;
            if (manualStartInstruction.LastRunTime == null || manualStartInstruction.LastRunTime.Value.Add(manualStartInstruction.Span) <= now)
            {
                instruction.LastRunTime = now;
                instruction.NextRunTime = now + instruction.Span;
                ManualStartOutput output = new ManualStartOutput
                {
                    ComponentID = this.ComponentID,
                    FinishTime = DateTime.Now,
                    JobID = Guid.NewGuid()
                };
                return new ResultBase[] { output };
            }
            else
                return null;
        }

        #endregion
    }
}
